/* eslint-disable jsx-a11y/anchor-is-valid */
/*
 * @Author: 周海 zhouhaib@yonyou.com
 * @Date: 2022-09-30 19:21:44
 * @LastEditors: 周海 zhouhaib@yonyou.com
 * @LastEditTime: 2022-12-06 21:17:56
 */
/* eslint-disable @typescript-eslint/no-unused-vars */
import React, { useEffect, useRef, useState } from 'react';
import TreeCardLayout from '@/components/treeCardLayout';
import { getDictDatasByDictTypes } from '@/api/system/dictData';
import { DictDataDomain } from '@/type.d/system';
import { useStore } from '@/store';
import { AjaxResult } from '@/type.d';
import { createIcon } from '@/utils';
import request from "@/utils/request";
import { ProFormInstance, BetaSchemaForm, ProFormColumnsType, ProCard, EditableProTable, ProColumns, ActionType, ProFormTreeSelect } from '@ant-design/pro-components';
import { Tree, Button, message, Radio, Popconfirm, Space, TreeSelect } from 'antd';
import { v4 as uuidv4 } from 'uuid';
import {
    treeselect,
    getDept,
    addDept,
    delDept,
    updateDept,
} from '@/api/system/dept';
import { SysDeptDomain } from '@/type.d/system/dept';
import './index.less';
import { corpTreeSelect } from '@/api/system/corp';
import { bulidTreeOptions } from '@/utils/tree';
import { NULL } from 'sass';


const Dept: React.FC = () => {
    const { layoutStore,userStore } = useStore();

    const [pkCorp, setPkCorp] = useState<string>();

    const [corpTree, setCorpTree] = useState<any[]>([]);

    const [treeDatas, setTreeDatas] = useState<any[]>([{key: '0',title: '部门',children: []}]);//所有菜单树数据

    const [disabled, setDisabled] = useState<boolean>(true);//表单是否编辑态

    const [selectdata, setSelectdata] = useState<SysDeptDomain>({});//选中的菜单树数据

    const [selectedTreeKeys, setSelectedTreeKeys] = useState<string[]>([]);//选中的菜单树主键

    const [oldSelectdata, setOldSelectdata] = useState<SysDeptDomain>();//编辑状态临时保存选中的菜单树数据

    const formRef = useRef<ProFormInstance<SysDeptDomain>>();//表单ref

    const [sysJobStatusOptions, setSysJobStatusOptions] = useState<any[]>([]);


    const newdata = {

    }


    /**
     * 表单字段配置
     */
    const formConfig: ProFormColumnsType<SysDeptDomain>[] = [
        {
            title: '部门id',
            key: 'deptId',
            colProps: { md: 8, xl: 6 },
            valueType: 'text',
            hideInForm: true,
        },
        {
            title: '公司主键',
            key: 'pkCorp',
            colProps: { md: 8, xl: 6 },
            valueType: 'text',
            hideInForm: true,
        },
        {
            title: '父部门id',
            key: 'parentId',
            colProps: { md: 8, xl: 6 },
            valueType: 'text',
            hideInForm: true,
        },
        {
            title: '祖级列表',
            key: 'ancestors',
            colProps: { md: 8, xl: 6 },
            valueType: 'text',
            hideInForm: true,
        },
        {
            title: '部门编码',
            key: 'deptCode',
            colProps: { md: 8, xl: 6 },
            valueType: 'text',
        },
        {
            title: '部门名称',
            key: 'deptName',
            colProps: { md: 8, xl: 6 },
            valueType: 'text',
        },
        {
            title: '显示顺序',
            key: 'orderNum',
            colProps: { md: 8, xl: 6 },
            valueType: 'text',
        },
        {
            title: '负责人',
            key: 'leader',
            colProps: { md: 8, xl: 6 },
            valueType: 'text',
        },
        {
            title: '联系电话',
            key: 'phone',
            colProps: { md: 8, xl: 6 },
            valueType: 'text',
        },
        {
            title: '邮箱',
            key: 'email',
            colProps: { md: 8, xl: 6 },
            valueType: 'text',
        },
        {
            title: '部门状态',
            key: 'status',
            colProps: { md: 8, xl: 6 },
            valueType: 'radio',
            fieldProps: {
                options: sysJobStatusOptions

            },
        },
        {
            title: '备注',
            key: 'remark',
            colProps: { md: 8, xl: 6 },
            valueType: 'text',
        },
        {
            title: '删除标志',
            key: 'delFlag',
            colProps: { md: 8, xl: 6 },
            valueType: 'text',
            hideInForm: true,
        },
        {
            title: '创建者',
            key: 'createBy',
            colProps: { md: 8, xl: 6 },
            valueType: 'text',
            fieldProps: {
                disabled: 'true'
            }
        },
        {
            title: '创建时间',
            key: 'createTime',
            colProps: { md: 8, xl: 6 },
            valueType: 'dateTime',
            fieldProps: {
                disabled: 'true'
            }
        },
        {
            title: '更新者',
            key: 'updateBy',
            colProps: { md: 8, xl: 6 },
            valueType: 'text',
            fieldProps: {
                disabled: 'true'
            }
        },
        {
            title: '更新时间',
            key: 'updateTime',
            colProps: { md: 8, xl: 6 },
            valueType: 'dateTime',
            fieldProps: {
                disabled: 'true'
            }
        },
    ];

    /**
     *
     * @param selectedKeys 菜单树选中事件
     * @param info
     * @returns
     */
    const onSelect = (selectedKeys: (string | number)[], info: any) => {
        if (!selectedKeys || selectedKeys.length === 0 ) {
            return
        }

        if(selectedKeys[0] === '0'){
            setSelectedTreeKeys(selectedKeys as string[])//选中的是根目录
            return
        }
        layoutStore.OpenSpanning()
        getDept(selectedKeys[0] as string).then((res) => {
            setSelectdata(res.data)
        }).finally(() => {
            setSelectedTreeKeys(selectedKeys as string[])
            layoutStore.CloseSpanning()
        })

    };

    /**
     * 根据后台返回的数据，组装成前端树组件需要的数据格式
     * @param datas
     * @returns
     */
    const buildTreeData = (datas: any[]): any[] => {
        return datas.map((data: any) => {
            return {
                title: data.dictLabel,
                key: data.dictValue,
                icon: createIcon(data.icon),
                children: data.children ? buildTreeData(data.children) : [],
            };
        });
    };

    /**
     * 页面加载完成后，调用后台查询树的数据
     */
    const getTreeDatas = (_pkCorp?: string) => {
        if(_pkCorp){
            layoutStore.OpenSpanning()
            treeselect({ pkCorp: _pkCorp }).then((res: AjaxResult) => {
                if (res.code === 200) {
                    treeDatas[0].children = buildTreeData(res.data);
                    setTreeDatas([...treeDatas]);
                }
            }).finally(() => {
                layoutStore.CloseSpanning();
            });
        }else{
            treeDatas[0].children = [];
            setTreeDatas([...treeDatas]);
        }
        
    };

    useEffect(() => {
        layoutStore.OpenSpanning()
        corpTreeSelect().then((res) => {
            if (res.data) {
                setCorpTree(bulidTreeOptions(res.data, 'pkCorp', 'corpName', 'children'))
            } else {
                setCorpTree([])
            }
        }).finally(() => {
            layoutStore.CloseSpanning()
        })
        //初始化完成，加载枚举类数据
        layoutStore.OpenSpanning();
        getDictDatasByDictTypes('sys_job_status').then((res) => {
            const data = res.data;
            if (data['sysJobStatus']) {
                const d: [] = data['sysJobStatus'];
                setSysJobStatusOptions(d.map((item: DictDataDomain) => {
                    return {
                        label: item.dictLabel,
                        value: item.dictValue
                    }
                }))
            }
        }).finally(() => {
            layoutStore.CloseSpanning()
        })
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    useEffect(() => {
        console.log('pkCorp',pkCorp);
        
        if (pkCorp) {
            getTreeDatas(pkCorp);
            setSelectdata({})
        } else {
            treeDatas[0].children = [];
            setTreeDatas([...treeDatas]);
            setSelectdata({})
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [pkCorp])

    useEffect(() => {
        console.log('selectdata',selectdata);
        //选中的数据发生变化时，更新右侧form表单
        if (selectdata && Object.keys(selectdata).length !== 0) {
            console.log('selectdata',1);
            formRef.current?.setFieldsValue(selectdata);
        } else {
            console.log('selectdata',2);
            formRef.current?.setFieldsValue({});
            formRef.current?.resetFields()
            setSelectedTreeKeys([])
        }

    }, [selectdata]);

    const onFormAdd = () => {
        if(!pkCorp){
            message.warning('请选择公司！')
            return
        }
        if (selectedTreeKeys && selectedTreeKeys.length === 1) {
            setOldSelectdata({ ...selectdata })//编辑时临时保存
            setSelectdata({ ...newdata,pkCorp, 'parentId': selectedTreeKeys[0] })
            setDisabled(false);
        } else {
            message.warning('请先选中一条数据')
        }
    }

    const onFormSave = () => {
        const newdata = formRef.current?.getFieldFormatValueObject?.() || {}
        layoutStore.OpenSpanning()
        const id = newdata?.deptId
        if (!id) {
            delete newdata?.deptId
            addDept(newdata).then((res) => {
                setSelectdata(res.data)
                setSelectedTreeKeys([res.data.deptId])
                //重新刷新左侧树的数据
                getTreeDatas(pkCorp);
                setDisabled(true)
                message.success('保存成功')
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        } else {
            updateDept(newdata).then((res) => {
                setSelectdata(res.data)
                setSelectedTreeKeys([res.data.deptId])
                //重新刷新左侧树的数据
                getTreeDatas(pkCorp);
                setDisabled(true)
                message.success('保存成功')
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        }


    }

    const onFormEdit = () => {
        if (selectdata && selectdata.deptId) {
            setOldSelectdata({ ...selectdata })//编辑时临时保存
            setDisabled(false);
        } else {
            message.warning('请先选中一条数据')
        }

    }

    const onFormDelete = () => {
        if (selectdata && selectdata.deptId) {
            layoutStore.OpenSpanning()
            delDept(selectdata.deptId).then((res) => {
                getTreeDatas(pkCorp);
                setSelectdata({})
                setSelectedTreeKeys([])
                message.success('删除成功！');
            }).catch((e) => {
                console.log('删除报错了');
                throw new Error(e)
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        } else {
            message.warning('请先选中一条数据')
        }

    }

    const onFormCancel = () => {
        if (selectedTreeKeys && selectedTreeKeys.length === 1) {
            setSelectdata({ ...oldSelectdata })//更新回编辑时临时保存
            setOldSelectdata({})
            setDisabled(true);
        }
    }

    const rendHeadButton = (_isedit: boolean) => {
        return _isedit ?
            <Space>
                <Button
                    key="save"
                    type="primary"
                    size='small'
                    onClick={onFormSave}
                >
                    保存
                </Button>
                <Button
                    key="cancel"
                    type="primary"
                    size='small'
                    onClick={onFormCancel}
                >
                    取消
                </Button>
            </Space> : <Space>
                <Button
                    hidden={!userStore.hasPerms('system:dept:add')}
                    key="add"
                    type="primary"
                    size='small'
                    onClick={onFormAdd}
                >
                    新增
                </Button>
                <Button
                    hidden={!userStore.hasPerms('system:dept:edit')}
                    key="edit"
                    type="primary"
                    size='small'
                    onClick={onFormEdit}
                >
                    修改
                </Button>
                <Button
                    hidden={!userStore.hasPerms('system:dept:remove')}
                    key="delete"
                    type="primary"
                    size='small'
                    onClick={onFormDelete}
                >
                    删除
                </Button>
            </Space>
    }

    const corpChange = (value: string) => {
        console.log('corp', value);
        setPkCorp(value)
    }
    return (
        <TreeCardLayout
            title={'部门'}
            titleIcon={'MenuUnfoldOutlined'}
            titleReactNode={<TreeSelect
                placeholder="请选择公司"
                treeDefaultExpandAll
                onChange={corpChange}
                value={pkCorp}
                treeIcon
                treeLine
                style={{ width: '250px' }}
                dropdownStyle={{ maxHeight: 600, overflow: 'auto' }}
                treeData={corpTree}
            />}
            headButton={rendHeadButton(!disabled)}
            treeNode={
                <Tree
                    defaultExpandParent
                    defaultExpandedKeys={['0']}
                    showLine={true}
                    showIcon={true}
                    onSelect={onSelect}
                    treeData={treeDatas}
                    selectedKeys={selectedTreeKeys}
                />
            }
            cardNode={
                <div className='card'>
                    <div className='form'>
                        <BetaSchemaForm<SysDeptDomain>
                            labelCol={{ flex: '120px' }}
                            wrapperCol={{ flex: 1 }}
                            layout={'horizontal'}
                            grid={true}
                            rowProps={{
                                gutter: [16, 0],
                            }}
                            disabled={disabled}
                            formRef={formRef}
                            initialValues={selectdata}
                            columns={formConfig}
                            submitter={{
                                render: (_, dom) => <>{ }</>,
                            }}
                        />
                    </div>
                </div>

            }
        />
    );
};
export default Dept;